//我的文章页
var ArticlePage=React.createClass({
  getInitialState:function () {
    return {
      sortType:0,
      level:0,
      articleIdForDetail:"",
      manageOn: false,
      chosenArticle: ""
    };
  },
  setChosenArticleId: function(id) {
    this.setState({
      chosenArticle: id
    });
  },
  changeSortType:function (type) {
    this.setState({
      sortType:type
    });
    this.reloadArticleList();//触发文章列表更新
  },
  toggleManageType: function() {
    console.log(this.state.manageOn)
    this.setState({
      manageOn: !this.state.manageOn
    })
  },
  toArticleDetail:function (id) {
    this.setState({
      level:1,
      articleIdForDetail:id
    });//跳转到文章详情页
  },
  toArticleList:function() {
    this.setState({
      level:0
    });//跳转到文章列表
  },
  imgFiles:[],//定义存放图片对象
  componentDidMount:function(){
    //定义获取图片信息并进行检验函数
    var self=this;
    function getFiles_article(e) {
      // isUpload = false;
      e = e || window.event;
      //获取file input中的图片信息列表
      var files = e.target.files,
        //验证是否是图片文件的正则
        reg = /image\/.*/i,
        fileType,
        fileName,
        fileNames="";

      for(var i=0,len=files.length;i<len;i++){
        fileType = files[i].type;
        fileName = files[i].name; 
        if (!reg.test(fileType)) {
          alert("你选择的" + fileName + "文件不是图片");
          self.imgFiles.splice(0,self.imgFiles.length);//清空数组
          return;
        }
        self.imgFiles.push(files[i]);
        fileNames+=fileNames==""?fileName:","+fileName;
      }
      if(fileNames.length>50){
        fileNames=fileNames.substring(0,50)+"...";//截取过长字符串
      }
      fileNames+="等"+len+"个文件";
      $(".selectedFileName").text(fileNames);//提示选择的文件
      
    }
    $("#uploadImg").on("click", function() {
      var $selectFile = $($("#writeModal form")[0]).find("input[type=file]");
      $selectFile.click();
    });

    //能力检测
    if (window.File && window.FileList && window.FileReader && window.Blob) {
      $("#fileInput").on("change", getFiles_article);
      //filesInput.addEventListener("change", getFiles, false);
      //submitUploadImg = uploadImgClient;
    } else {
      console.log("您的浏览器不支持HTML5长传");
      //submitUploadImg = uploadImgServer;
    }

    $("#publishBtn").on("click", function(event) {


      event.preventDefault();
      if (self.validate()) {

        if (self.imgFiles.length == 0) {
          //直接发布文章
          self.publishArticle([]);
        } else {

          //上传文件，然后发布文章

          $("#publishBtn").attr("disabled", "disabled") //禁用上传按钮
          .text("上传中");
          uploadImgFiles(self.imgFiles,self.publishArticle);
        }

      }
    });
    $("#saveBtn").on("click",function(){
      self.saveDraft();
    });
    this.checkDraft();

    $("#updateBtn").on("click", function(event) {
      event.preventDefault();
      if (self.validate()) {

        if (self.imgFiles.length == 0) {
          //直接发布文章
          self.updateArticle([]);
        } else {

          //上传文件，然后发布文章

          $("#updateBtn").attr("disabled", "disabled") //禁用上传按钮
          .text("上传中");
          uploadImgFiles(self.imgFiles,self.updateArticle);
        }

      }
    })

    $("#writeDescription").editable({
      inlineMode: false,

       buttons: ['bold', 'italic', 'underline', 'strikeThrough', 'fontFamily', 'fontSize', 'color', 'formatBlock', 'blockStyle', 'inlineStyle', 'align', 'insertOrderedList', 'insertUnorderedList', 'outdent', 'indent', 'selectAll', 'createLink', 'table', 'undo', 'redo', 'html', 'insertHorizontalRule', 'removeFormat', 'fullscreen']
    });
  },
  //用本地储存保存草稿
  saveDraft:function (){
    var description=$($("#writeDescription .froala-view")[0]).html();
    var title=$("#writeTitleInput").val();
    localStorage.setItem("draft_description",description);
    localStorage.setItem("draft_title",title);
  },
  //清除草稿
  clearDraft:function (){
    localStorage.removeItem("draft_description");
    localStorage.removeItem("draft_title");
  },
  //检查是否有草稿
  checkDraft:function (){
    var d=localStorage.getItem("draft_description",description);
    var t=localStorage.getItem("draft_title",title);
    if(d||t){
      var description=$($("#writeDescription .froala-view")[0]).html(d);
      var title=$("#writeTitleInput").val(t);
    }
  },
  //在提交问题前检验数据是否合法

 validate: function () {
    var errMsg = "";
    var description = $($("#writeDescription .froala-view")[0]).html();
    if (description == "") {
      errMsg += "文章正文不能为空 ";
    }
    if ($("#writeTitleInput").val() == "") {
      errMsg += "文章标题不能为空 ";
    }
    if (cookie.getCookie("studioId") == "") {
      errMsg += "请先登录";
    }
    if (errMsg != "") {
      alert(errMsg);
      return false;
    } else {

      return true;
    }
  },

  emptyInput:function () {
    $($("#writeDescription .froala-view")[0]).html("");
    $("#writeTitleInput").val("");
    $(".selectedFileName").text("");
    var fileInput = $("#fileInput")
    fileInput.after(fileInput.clone().val(""));
    fileInput.remove();
  },

  publishArticle:function (responseUrls){
    var self=this;
    var studioId=cookie.getCookie("studioId");
    var description = escape($($("#writeDescription .froala-view")[0]).html());
    var title=$("#writeTitleInput").val();
    $.ajax({
      url:config.api.publishArticle[0].replace(/\<\w+\>/,studioId),
      type:config.api.publishArticle[1],
      data:{
        title:title,
        content:description,
        images:JSON.stringify(responseUrls)
      },
      success:function(){
        //responseUrls.splice(0,responseUrls.length);//清空
        $("#publishBtn").text("发表成功");
        setTimeout(function(){
          $('#writeModal').modal('hide');
          $("#publishBtn").text("立即发布").removeAttr("disabled");
          self.emptyInput();
          self.clearDraft();
          self.reloadArticleList();
        },2000);
      },
      error:function(){
        alert("发表失败");
      }
    });
  },
  updateArticle: function(responseUrls) {
    var self=this;
    var studioId=cookie.getCookie("studioId");
    var description = escape($($("#writeDescription .froala-view")[0]).html());
    var title=$("#writeTitleInput").val();
    $.ajax({
      url:config.api.updateArticle[0].replace(/\<\w+\>/,studioId),
      type:config.api.updateArticle[1],
      data:{
        title:title,
        content:description,
        images:JSON.stringify(responseUrls)
      },
      success:function(){
        //responseUrls.splice(0,responseUrls.length);//清空
        $("#updateBtn").text("编辑成功");
        setTimeout(function(){
          $('#writeModal').modal('hide');
          $("#updateBtn").text("完成编辑").removeAttr("disabled");
          self.emptyInput();
          self.clearDraft();
          self.reloadArticleList();
        },2000);
      },
      error:function(){
        alert("编辑失败");
        setTimeout(function(){
          $('#writeModal').modal('hide');
          $("#updateBtn").text("完成编辑").removeAttr("disabled");
          self.emptyInput();
          self.clearDraft();
          self.reloadArticleList();
        },2000);
      }
    });
  },
  reloadArticleList:function(){
    this.refs.theList.reload(this.state.sortType);
  },
  render:function(){
    var content=null;
    if(this.state.level==0){
      content=<div>
                <ArticleActionBar sortType={this.state.sortType} changeSortType={this.changeSortType} toggleManageType={this.toggleManageType}/>
                <ArticleList studioName={this.props.studioName} studioAvatar={this.props.studioAvatar} ref="theList" toArticleDetail={this.toArticleDetail} manageOn={this.state.manageOn} setChosenArticleId={this.setChosenArticleId}/>
              </div>;
    }else{
      content=<ArticleDetail articleId={this.state.articleIdForDetail} toArticleList={this.toArticleList}/>;
    }
    return (
      <div className="ArticlePageContainer">
        {content}
        <div className="modal fade" id="writeModal" tabindex="-1" role="dialog" aria-labelledby="writeModalLabel" aria-hidden="true">
          <div className="modal-dialog modal-lg">
            <div className="modal-content writeContainer">
              <div className="writeBody">
                <div className="writeInput">
                  <input type="text"  id="writeTitleInput" placeholder=" 输入标题"/>
                </div>
                <div className="writeToolBar"></div>
                <div className="writeInput">
                  <div className="uploadMediaBtn" id="uploadImg"></div>
                  <div className="uploadMediaBtn" id="uploadVideo"></div>
                  <p className="selectedFileName"></p>
                  <div id="writeDescription">
                    输入文章正文
                  </div>
                  <form enctype="multipart/form-data" action="msq/api/image" method="POST" target="hidden_frame">
                    <input type="file" name="image" id="fileInput" multiple="multiple"/>
                    <input type="submit" id="uploadBtn"/>
                  <iframe name='hidden_frame' id="hidden_frame"></iframe> 
                  </form> 
                </div>
                <div className="actionBtns">
                  <button className="btn btn-primary btn-md" id="publishBtn">立即发布</button>
                  <button className="btn btn-primary btn-md" id="updateBtn">编辑完成</button>
                  <button className="btn btn-default btn-md" id="saveBtn">保存草稿</button>       
                </div>
              </div>
            </div>
            <div className="cancel" aria-hidden="true" data-dismiss="modal">
            </div>
          </div>
          
        </div>
      </div>

      );
    }
});
var ArticleActionBar=React.createClass({
  sortByTime:function(){
    console.log("sortByTime");
    this.props.changeSortType(0);
  },
  sortByHeat:function(){
    console.log("sortByHeat");
    this.props.changeSortType(1);
  },
  manageOn: function() {
    
  },
  openModal: function(e) {
    if (e.target.innerHTML.indexOf("写文章") != -1) {
      $("#writeModal").find("#updateBtn").hide()
      .end().modal({
        "backdrop": "static",
        "show": true
      });
    }
  },
  render:function(){
    if(this.props.sortType==0){
      return (
        <div className="articleActionBar">
          <div id="sortByTime" className="sortBtn active" onClick={this.sortByTime}><span>时间</span></div>
          <div id="sortByHeat" className="sortBtn" onClick={this.sortByHeat}><span>热度</span></div>
          <div id="writeArticle"  onClick={this.openModal} ><span>写文章</span></div>
          <div id="manage" onClick={this.props.toggleManageType}><span>管理</span></div>
        </div>
        );
    }else{
      return (
        <div className="articleActionBar">
          <div id="sortByTime" className="sortBtn" onClick={this.sortByTime}><span>时间</span></div>
          <div id="sortByHeat" className="sortBtn active" onClick={this.sortByHeat}><span>热度</span></div>
          <div id="writeArticle" data-toggle="modal" data-target="#writeModal"><span>写文章</span></div>
          <div id="manage" onClick={this.props.toggleManageType}><span>管理</span></div>
        </div>
        );
    }

  }
});
//文章列表
var ArticleList=React.createClass({
  getInitialState:function(){
    return {
      articles:null
    }
  },
  componentDidMount:function(){
    var studioId=cookie.getCookie("studioId");
    $.ajax({
      url:"msq/api/studio/<studio_id>/article".replace(/\<\w+\>/,studioId),
      type:"GET",
      data:{
        sort:0,// 0 表示按照时间排序，1 表示按照热度排序，默认为 0
        total:-1// -1代表全部返回
      },
      success:function(d){
        this.setState({articles:d.articles});
         console.log(this.state);
      }.bind(this),
      error:function(){
        alert("获取数据出错");
      }
    });
  },
  reload:function(sortType){
    var studioId=cookie.getCookie("studioId");
    $('.article-delete').addClass('hidden');
    $.ajax({
      url:"msq/api/studio/<studio_id>/article".replace(/\<\w+\>/,studioId),
      type:"GET",
      data:{
        sort:sortType,// 0 表示按照时间排序，1 表示按照热度排序，默认为 0
        total:-1// -1代表全部返回
      },
      success:function(d){
        this.setState({articles:d.articles});
      }.bind(this),
      error:function(){
        alert("刷新出错");
      }
    });
  },
  showAllHandler:function(e) {
    this.props.toArticleDetail($(e.target).data("articleid"));
  },
  remove: function(e) {
    var studioId = cookie.getCookie("studioId");
    var target = e.target;
    if (confirm("你真的要删除该文章吗？")) {
      $.ajax({
        url: config.api.deleteArticle[0].replace(/\<\w+\>/,$(target).data("articleid")),
        type:config.api.deleteArticle[1],
        success: function() {
          this.reload();
        }.bind(this),
        error: function() {
          alert("删除失败");
        }
      });
    }
  },
  update: function() {
    alert("此功能暂无,攻城狮们正在加班加点实现");
  },
  openModal: function(self, event) {
    var articleId = $(event.target).data("articleid");
    if (event.target.innerHTML.indexOf("编辑") != -1) {
      
      $("#writeModal").find("#publishBtn").hide()
      .end().modal({
        "backdrop": "static",
        "show": true
      });
      self.getArticleContent(articleId);
      self.props.setChosenArticleId(articleId);
    }
  },
  getArticleContent: function(articleId) {
    $.ajax({
      url:config.api.getArticleDetail[0].replace(/\<\w+\>/, articleId),
      type:config.api.getArticleDetail[1],
      success:function(d){
        this.addAritcleContent(d.article);
      }.bind(this),
      error:function(e) {
        alert("获取文章详情失败")
      }
    });
  },
  addAritcleContent: function(articleDetail) {
    $("#writeTitleInput").val(articleDetail.title);
    $($("#writeDescription .froala-view")[0]).empty().append(unescape(articleDetail.content));
  },
  render:function(){
    var articlesContent;
    var self=this;
    if(this.state.articles===null){
      articlesContent=<p>文章加载中</p>;
    }else{
      var studioName=this.props.studioName;
      var avatarUrl=this.props.studioAvatar;
      function   formatDate(now)   {     
                    var   year=now.getYear()+1900;     
                    var   month=now.getMonth()+1;     
                    var   date=now.getDate();     
                    var   hour=now.getHours();     
                    var   minute=now.getMinutes();       
                    return   year+"-"+month+"-"+date+"   "+hour+":"+(minute<10?"0"+minute:minute);     
                    }     
      articlesContent=this.state.articles.map(function(article){
        var images=article.images.map(function(image){
          return (
            <img src={image}/>
            );
        });
        var createTime=new Date(article.createTime);
        console.log(self.props.manageOn);
        return(
        <div className="article" >
          <div className="left-col">
            <div className="avatarWrapper">
              <img src={avatarUrl}/>
            </div>
            <div className="triangle"></div>
          </div> 
          <div className="right-col">
            <div className="problem-details">
              <h5>{studioName}</h5>
              <h6>{formatDate(createTime)}</h6>
              <div className="showArticleContent" ref={function(articleDiv) {
                if (articleDiv != null) {
                  $(articleDiv.getDOMNode()).empty().append(unescape(article.content));
                }
              }}>
              </div>
              <div className="paintings">
                {images}
              </div>
              <div className="tags-showAll">
                <span className="showAll" data-articleid={article.articleId} onClick={self.showAllHandler}>显示全部</span>
                <span className={(self.props.manageOn)?"article-delete": "article-delete hidden"} data-articleid={article.articleId} onClick={self.remove}>删除</span>
                <span className={(self.props.manageOn)?"article-update": "article-update hidden"} data-articleid={article.articleId} onClick={self.openModal.bind(null, self)}>编辑</span>
              </div>
            </div>
          </div> 
        </div>
        );
      });
    }
    return (
      <div>
        {articlesContent}
      </div>
      );
  }
});
//文章详情页
var ArticleDetail=React.createClass({
  getInitialState:function(argument) {
    return {
      article:null,
      loaded:false
    };
  },
  componentDidMount:function(){
    $.ajax({
      url:config.api.getArticleDetail[0].replace(/\<\w+\>/,this.props.articleId),
      type:config.api.getArticleDetail[1],
      success:function(d){
        this.setState(
              {
                article:d.article,
                loaded:true
              }
          );
      }.bind(this),
      error:function(e) {
        alert("获取文章详情失败")
      }
    });
  },
  formatDate:function(timestamp){  
                var dateObj=new Date(timestamp);   
                var   year=dateObj.getYear()+1900;     
                var   month=dateObj.getMonth()+1;     
                var   date=dateObj.getDate();     
                var   hour=dateObj.getHours();     
                var   minute=dateObj.getMinutes();       
                return   year+"-"+month+"-"+date+"   "+hour+":"+(minute<10?"0"+minute:minute);     
  }, 
  render:function() {
    if(this.state.loaded){
      var data=this.state.article;
      return (
      <div className="articleDetail">
        <div className="breadcrumb">
          <span onClick={this.props.toArticleList}>我的文章</span>
          <span>&gt;</span>
          <span>文章详情</span>
        </div>
        <div className="articles">
          <h5>{data.title}</h5>
          <h6>{this.formatDate(data.createTime)}</h6>
          <div ref={function(articleContentDiv) {
            if (articleContentDiv != null) {
              $(articleContentDiv.getDOMNode()).empty()
              .append(unescape(data.content));
            }
          }}>
          </div>
          <div className="paintings">
            {
              data.images.map(function(image) {
                return (
                  <img src={image} alt=""/>
                  );
              })
            }
          </div>
          <div className="tags-showAll">
            <span className="tags viewNum">点击{data.viewNum}</span>
          </div>
        </div>
      </div>

        );
    }else{
      return (
        <div className="articleDetail">
          <div className="breadcrumb">
            <span onClick={this.props.toArticleList}>我的文章</span>
            <span>&gt;</span>
            <span>文章详情</span>
          </div>
          <p>文章详情加载中</p>
        </div>
        );
    }

  }
});